package com.eco.fanliapp.job.dtkitemjob;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.entity.GoodsFree;
import com.eco.fanliapp.entity.SyChannelGoods;
import com.eco.fanliapp.entity.SyTljGoodsfree;
import com.eco.fanliapp.service.IAppGoodsService;
import com.eco.fanliapp.service.RedisTemplateService;
import com.eco.fanliapp.utils.Convert;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 获取大淘客失效商品
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class DTKStaleGoodsTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(DTKStaleGoodsTask.class);

    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private SyLabelGoodsMapper syLabelGoodsMapper;
    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private SyChannelGoodsMapper syChannelGoodsMapper;
    @Autowired
    private GoodsFreeMapper goodsFreeMapper;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private SyTljGoodsfreeMapper syTljGoodsfreeMapper;

    public DTKStaleGoodsTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执行获取大淘客失效商品定时任务-DTKItemTask：executeCount=" + executeCount + "--beginTime=" + beginTime);

        //每十分钟执行一次
        long startTime = System.currentTimeMillis();
        String pageId = "1";
        String pageSize = "200";
        while (true) {
            try {
                String result = daTaoKeItemInfoService.getStaleGoods(pageSize, pageId);
                Integer code = JSONObject.parseObject(result).getInteger("code");
                if (code != 0) {
                    break;
                }
                result = JSONObject.parseObject(result).getString("data");
                String pageid = JSONObject.parseObject(result).getString("pageId");
                JSONArray array = JSONArray.parseArray(JSONObject.parseObject(result).getString("list"));
                if (array == null || array.size() <= 0) {
                    break;
                }
                List<String> goodsIdList = new ArrayList<>();
                String itemids = "";
                for (int i = 0; i < array.size(); i++) {
                    AppGoods appGoods = appGoodsService.findAppGoodsByItemId(array.getJSONObject(i).getString("goodsId"));

                    if (appGoods != null) {
                        if (appGoods.getAddUserId() != null && appGoods.getRecommend() == 1 && appGoods.getAddUserId() == -115) {
                            continue;
                        }
                        SyChannelGoods syChannelGoods = syChannelGoodsMapper.selectChannelGoodsById(Long.valueOf(appGoods.getItemid()));
                        HashMap<String, Object> goodsFreeMap = new HashMap<>();
                        goodsFreeMap.put("goodsId", appGoods.getItemid());
                        goodsFreeMap.put("goodsStatus", 2);
                        List<GoodsFree> goodsFree = goodsFreeMapper.selectByGoodsIds(goodsFreeMap);
                        SyTljGoodsfree syTljGoodsfree = syTljGoodsfreeMapper.selectTljGoodsfreeByItemId(Long.valueOf(appGoods.getItemid()));
                        if (syChannelGoods == null && syTljGoodsfree == null && goodsFree.size() == 0) {
                            goodsIdList.add(array.getJSONObject(i).getString("goodsId"));
                            itemids += array.getJSONObject(i).getString("goodsId") + ",";
                        }
                    }

                }
                if (goodsIdList.size() > 0) {
                    int i = appGoodsMapper.deleteAppGoodsByItemid(goodsIdList.toArray(new String[goodsIdList.size()]));
                    if (i > 0) {
                        int ii = syLabelGoodsMapper.deleteByItemIds(goodsIdList.toArray(new String[goodsIdList.size()]));
                        //删除缓存app_fixedSortGoods_list中商品的固定排序
                        String fixedSort_key = "app_fixedSortGoods_list";
                        if (redisTemplateService.hasKey(fixedSort_key)) {
                            String[] fixedSortItemids = Convert.toStrArray(itemids);
                            for (int y = 0; y < fixedSortItemids.length-1; y++) {
                                redisTemplateService.delMapField(fixedSort_key, fixedSortItemids[y]);
                            }
                        }
//                        appGoodsService.deleteIndex(itemids, "delete");
                        log.info("删除失效商品   message商品表数据删除成功{}--ids={}", i, goodsIdList.toString());
                    }
                }

                pageId = pageid;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取大淘客失效商品错误");
                break;
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行获取大淘客失效商品定时任务任务-DTKItemTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }
}
